﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using kysec.RAL.EFToMySql;
using MySql.Data.MySqlClient;

namespace kysec.Bll.User
{
    public class common {
        /// <summary>
        /// 判断是否存在该用户，保证用户号的唯一性,根据用户名去判断
        /// </summary>
        /// <param name="username"></param>
        /// <returns>存在返回true，不存在返回false</returns>
        public static bool getUser(string username)
        {
            using (var db = new MySql_kysecContectionString())
            {
                bool list = db.tb_user.Any(c => c.c_vc_userName == username);
                db.Dispose();
                if (list)
                {
                    return true;
                }
            }
            return false;
        }
       
        /// <summary>
        /// 判断是否存在该用户，保证用户号的唯一性,根据用户ID去判断
        /// </summary>
        /// <param name="username"></param>
        /// <returns>存在返回true，不存在返回false</returns>
        public static bool getUser(Guid id)
        {
            using (var db = new MySql_kysecContectionString())
            {
                bool list = db.tb_user.Any(c => c.c_uq_userId.Equals(id));
                db.Dispose();
                if (list)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 根据用户ID得到用户名
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>返回用户名</returns>
        public static string getUserNameById(string id)
        {
            //using (var db = new MySql_kysecContectionString())
            //{
            Guid userId = Guid.NewGuid();
            if (id.Equals("password"))
                userId = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(HttpContext.Current.Session["userId"].ToString()));
            else
                userId = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(id));
            //string username=string.Empty;
            try
            {
                id = userId.ToString();
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();
                var list = ctx.tb_user.Where(c => c.c_uq_userId.Equals(id) && c.c_b_isOnline == true && c.c_b_isDelete == false).ToList();

                foreach (var item in list)
                {
                    //username = item.c_vc_userName;
                    return item.c_vc_userName;
                }
                ctx.Dispose();
            }
            catch (Exception ex)
            {

            }


            return null;
            //}
        }
    }

    public class userInfo
    {
        /// <summary>
        /// 添加用户基本信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns>成功返回1，失败返回0</returns>
        public static string AddUserInfo(tb_user model)
        {
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            string result = "0";
            Guid uId = Guid.NewGuid();
            string pwd = kysec.CR.Common.EncodeByBase64.Encode(model.c_vc_passWord);
            try
            {
                tb_user user = new tb_user {
                    c_uq_userId = uId.ToString(),
                    c_vc_userName = model.c_vc_userName,
                    c_vc_passWord = pwd,
                    c_dt_regDate = DateTime.Now,
                    c_b_isComplete = false,
                    c_b_isDelete = false,
                    c_b_isOnline = false,
                    c_i_pop = model.c_i_pop
                };
                ctx.AddObject("tb_user", user);
                if (AddUserDetailInfo(uId).Equals("1"))
                {
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch
            {
                kysec.CR.Logger.MyLogger.Error("插入用户数据发生异常……");
                result = "2";
            }
            finally
            {
                ctx.Dispose();
            }
            return result;
        }


        /// <summary>
        /// 添加到详细信息中，主要是创建一个详细信息的主键
        /// </summary>
        /// <param name="userId">用户的ID</param>   
        /// <returns>成功返回1，失败返回0 异常返回2</returns>
        public static string AddUserDetailInfo(Guid userId)
        {
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            string result = "0";
            try
            {
                tb_userinfo userInfo = new tb_userinfo {
                    c_uq_userId = userId.ToString(),
                    c_uq_cid = Guid.NewGuid().ToString()    
                };
                ctx.AddObject("tb_userinfo", userInfo);
                result = ctx.SaveChanges().ToString();
                return result;
            }
            catch
            {
                kysec.CR.Logger.MyLogger.Error("插入用户数据发生异常……");
                result = "2";
            }
            finally
            {
                ctx.Dispose();
            }
            return result;
        } 

        /// <summary>
        /// 实现图片的上传
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <returns>成功返回1，异常返回2.失败返回0</returns>
        public static string photoUpLoad(string id,string imgPath)
        {
            string result = "0";

            id = kysec.CR.Common.EncodeByBase64.Decode(id);

            
            MySql_kysecContectionString ctx=new MySql_kysecContectionString ();
            
            try
            {
                var list = ctx.tb_userinfo.Where(c => c.c_uq_userId.Equals(id)).ToList();

                foreach (var item in list)
                {
                    item.c_nvc_photo = imgPath;
                }
                result = ctx.SaveChanges().ToString();
            }
            catch (Exception ex)
            {
                kysec.CR.Logger.MyLogger.Error(typeof(userInfo), "头像添加异常"+ex.ToString());
                result = "2";
            }
            finally {
                ctx.Dispose();
            }
            return result;
        }


        /// <summary>
        /// 完成基本信息标志
        /// </summary>
        /// <param name="userId"></param>
        /// <returns>完善返回true，否则返回fasle</returns>
        public static bool isFinishInfo(string id)
        {
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            var list = ctx.tb_user.Where(c => c.c_uq_userId.Equals(id)).ToList();
            bool result = false;
            if (list.Count != 0)
            {
                try
                {
                    foreach (var item in list)
                    {
                        item.c_b_isComplete = true;
                    }
                    result = ctx.SaveChanges() == 1 ? true : false;
                }
                catch (Exception)
                {
                    return result;
                }
            }
            return result;
        }

       
        /// <summary>
        /// 添加或修改用户详细信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <returns>0:信息不存在，1:插入成功，2:插入数据是异常</returns>
        public static string FinishUserInfo(tb_userinfo model, string userId)
        {
            int count = 0;//定义是否找到该数据
            string result = "";//结果返回
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            userId = kysec.CR.Common.EncodeByBase64.Decode(userId);

            count = ctx.tb_user.Where(c => c.c_uq_userId.Equals(userId) && c.c_b_isComplete == false).Count();
            if (count == 0)
            {
                result = "0";
            }

            try
            {
                var list = ctx.tb_userinfo.Where(c => c.c_uq_userId.Equals(userId)).ToList();
                if (list.Count != 0)
                {
                    foreach (var item in list)
                    {
                        item.c_i_age = model.c_i_age;
                        item.c_nvc_address = model.c_nvc_address;
                        item.c_nvc_realname = model.c_nvc_realname;
                        item.c_nvc_sex = model.c_nvc_sex;
                        item.c_vc_mobile = model.c_vc_mobile;
                        item.c_vc_msn = model.c_vc_msn;
                        item.c_vc_phone = model.c_vc_phone;
                        item.c_vc_qq = model.c_vc_qq;
                    }

                    if (isFinishInfo(userId))
                    {
                        result = ctx.SaveChanges().ToString();
                    }
                }              
            }
            catch
            {                
                kysec.CR.Logger.MyLogger.Error("插入用户数据发生异常……");
                result = "2";
            }
            finally
            {
                ctx.Dispose();
            }
            return result;
        }


        /// <summary>
        /// 查询未完善用户的详细信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>返回找到的信息 </returns>
        public static List<tb_user> DetailsNotFinished(string id)
        {
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity().RetrieveObject(
                string.Format("id_{0}_notFinished", id));
            if (o == null)
            {
               id = kysec.CR.Common.EncodeByBase64.Decode(id);
                List<tb_user> list = ctx.tb_user.Where(c => c.c_uq_userId.Equals(id) && c.c_b_isComplete == false).ToList();
                ctx.Dispose();
                if (list.Count != 0)
                {
                    kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity().AddObjectWithAbsoluteTime(
                        string.Format("id_{0}_notFinished", id),
                        list,
                        10000,
                        System.Web.Caching.CacheItemPriority.Normal);
                    return list;
                }
            }
            return (List<tb_user>)o;
        }

        /// <summary>
        /// 查询已完善用户的详细信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>返回找到的信息 </returns>
        public static List<vw_tb_user> DetailsFinished(string id)
        {
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity().RetrieveObject(
                string.Format("id_{0}", id));
            if (o == null)
            {
                id =kysec.CR.Common.EncodeByBase64.Decode(id);
                List<vw_tb_user> list = ctx.vw_tb_user.Where(c => c.c_uq_userId.Equals(id)).ToList();
                ctx.Dispose();
                if (list.Count != 0)
                {
                    kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity().AddObjectWithAbsoluteTime(
                        string.Format("id_{0}", id),
                        list,
                        10000,
                        System.Web.Caching.CacheItemPriority.Normal);
                    return list;
                }
            }
            return (List<vw_tb_user>)o;
        }



        /// <summary>
        /// 删除或者恢复用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>0:没有找到信息，1:删除或恢复成功，2:删除或恢复时发生异常</returns>
        public static string DeleteUserInfo(string id,bool isDelete)
        {
            string result = "0";
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            if (!common.getUser(id))
            {
                result = "0";
            }
            else
            {                
                try
                {
                    bool isDel = false;

                    if (isDelete)
                        isDel = ctx.tb_user.Single(c => c.c_uq_userId.Equals(id)).c_b_isDelete = true;
                    else
                        isDel = ctx.tb_user.Single(c => c.c_uq_userId.Equals(id)).c_b_isDelete = false;

                    result = ctx.SaveChanges().ToString();
                }
                catch
                {
                    kysec.CR.Logger.MyLogger.Error(typeof(userInfo), "删除或恢复信息发生异常");
                    result = "2";
                }
                finally
                {
                    ctx.Dispose();
                }
                
            }
            return result;
        }
        
        /// <summary>
        /// 判断用户输入的旧密码是否于原密码一致
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="password">旧密码</param>
        /// <returns>若一致则返回true，否则返回false</returns>
        public static bool PwdIsRight(string id, string password)
        {
            using (var db=new MySql_kysecContectionString()) {
                id = kysec.CR.Common.EncodeByBase64.Decode(id);
                bool isExit = db.tb_user.Any(c => c.c_uq_userId.Equals(id) && c.c_vc_passWord == password);
                return isExit;
            }
        }
        /// <summary>
        /// 修改用户密码信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>0:没有找到信息，1:密码修改成功，2:密码修改时发生异常</returns>         
        public static string EditPwdInfo(string id, string password)
        {
            string result = "0";
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            var list = ctx.tb_user.Where(c => c.c_uq_userId.Equals(id)).ToList();

            if (list.Count == 0)
            {
                result = "0";
            }
            else
            {
                try
                {
                    foreach (var item in list)
                    {
                        item.c_vc_passWord = password;
                    }
                    result = ctx.SaveChanges().ToString();
                }
                catch
                {
                    kysec.CR.Logger.MyLogger.Error(typeof(userInfo), "修改密码发生异常");
                    result = "2";
                }
                finally
                {
                    ctx.Dispose();
                }
            }
            return result;
        }

        /// <summary>
        /// 修改基本信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>0:没有找到信息，1:修改成功，2:修改时发生异常</returns>
        public static string EditBasicInfo(string id, tb_user model)
        {
            string result = "0";
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);
            var list = ctx.tb_user.Where(c => c.c_uq_userId.Equals(id)).ToList();

            if (list.Count == 0)
            {
                result = "0";
            }
            else
            {
                try
                {
                    foreach (var item in list)
                    {
                        item.c_i_pop = model.c_i_pop;
                        item.c_vc_userName = model.c_vc_userName;
                    }
                    result = ctx.SaveChanges().ToString();
                }
                catch
                {
                    kysec.CR.Logger.MyLogger.Error(typeof(userInfo), "修改基本信息发生异常");
                    result = "2";
                }
                finally
                {
                    ctx.Dispose();
                }
            }
            return result;
        }
    }
}
